
import time, datetime
from pymongo import MongoClient
from bson import ObjectId
import pymysql
import traceback
import copy

dbs = {
    "mongo-dev": {
        "host": "10.246.247.194",
        "port": 27016,
        "username": "dev_xhhkmedical",
        "password": "Za3m4cC1hpCc8T6DB",
        "authSource": "dev_xhhkmedical"
    },
    "mongo-prod": {
        "host": "10.246.247.236",
        "port": 27016,
        "username": "xhhkmedical_read",
        "password": "pCc8T6DBZa3m4cC1h",
        "authSource": "xhhkmedical"
    }
}

mongodb_ins = MongoClient(**dbs["mongo-prod"]).xhhkmedical


def get_age_year(birth):
    if not birth:
        return 0
    if not isinstance(birth, str):
        birth = str(birth)
    birth = birth.strip()
    birth = birth.split(' ')[0]

    nowyear = datetime.datetime.now().year
    nowmonth = datetime.datetime.now().month
    nowday = datetime.datetime.now().day

    birth = birth.replace('-','/')
    sj_list = birth.split('/')
    if "/" not in birth:
        sj_list = [birth[:4], birth[4:6], birth[6:8]]

    age = ''
    age = abs(int(nowyear) - int(sj_list[0]))
    if int(nowmonth) < int(sj_list[1]):
        age = age - 1
    elif int(nowmonth) == int(sj_list[1]):
        if int(nowday) < int(sj_list[2]):
            age = age - 1

    return 1 if age == 0 else age


def do_query_hc():
    hcs = mongodb_ins.XHHK_HealthCard.find({
        "created_at": {
            "$gte": 1654012800000,
            "$lt": 1685548800000
        },
        "id_card": {"$nin": ["", None]}
    })
    count = 0
    i = 1
    for hc in hcs:
        birthdate_str = hc.get("id_card", "")[6:14]
        if not birthdate_str or len(birthdate_str) != 8:
            continue
        age = get_age_year(birthdate_str)
        if age > 45:
            count += 1
        print(i)
        i += 1
    print(1111111111, count)


def do_query_registerrecords():
    rrs = mongodb_ins.XHHK_RegisterRecord.aggregate([
        {
            "$match": {
                "order_time": {
                    "$gte": 1590940800000,
                    "$lt": 1622476800000
                },
                "patient_id": {"$nin": ["", None], "$exists": True},
                "obsoleted": False
            }
        },
        {
            "$lookup": {
                "from": "XHHK_Patient",
                "localField": "patient_id",
                "foreignField": "_id",
                "as": "pat"
            }
        },
        {
            "$unwind": {
                "path": "$pat",
                "preserveNullAndEmptyArrays": True
            }
        }
    ])
    count = 0
    i = 1
    for rr in rrs:
        pat = rr.get("pat")
        if not pat:
            continue
        birthdate_str = pat.get("id_number", "")[6:14]
        if not birthdate_str or len(birthdate_str) != 8:
            birthdate_st = pat.get("birthday")
            if not birthdate_st or "/" in str(birthdate_st) or "-" in str(birthdate_st) or len(str(int(birthdate_st))) != 10:
                continue
            if (int(time.time()) - int(1697990400))/3600/24/365 > 45:
                count += 1
            continue
        age = get_age_year(birthdate_str)
        if age > 45:
            count += 1
        print(i)
        i += 1
    print(1111111111, count)


def main():
    try:
        # do_query_hc()
        do_query_registerrecords()
    except Exception:
        print(traceback.format_exc())


if __name__ == '__main__':
    main()
